package offer.offer25;

/**
 * @Author: wjy
 * @Date: 2021/10/26 9:05
 */
public class Solution {

    public static void main(String[] args) {

        ListNode listNode1 = new ListNode(1);
        ListNode listNode2 = new ListNode(2);
        ListNode listNode3 = new ListNode(4);
        ListNode listNode4 = new ListNode(1);
        ListNode listNode5 = new ListNode(3);
        ListNode listNode6 = new ListNode(4);
        listNode1.next = listNode2;
        listNode2.next = listNode3;

        listNode4.next = listNode5;
        listNode5.next = listNode6;

        Solution solution = new Solution();
        ListNode res = solution.mergeTwoLists(listNode1, listNode4);

        while (true) {
            if (res == null) {
                break;
            }
            System.out.println(res.val);
            res = res.next;
        }

    }

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

        if (l1 == null && l2 == null) {
            return null;
        }

        ListNode node = null;

        if (l2 == null || (l1 != null && l1.val <= l2.val)) {
            node = l1;
            this.nodeList(l1.next, l2, node);
        }
        if (l1 == null || (l2 != null && l1.val > l2.val)) {
            node = l2;
            this.nodeList(l1, l2.next, node);
        }

        return node;

    }

    public void nodeList (ListNode l1, ListNode l2, ListNode node) {

        if (l1 == null && l2 == null) {
            return;
        }

        if (l2 == null || (l1 != null && l1.val <= l2.val)) {
            node.next = l1;
            this.nodeList(l1.next, l2, node.next);
        }
        if (l1 == null || (l2 != null && l1.val > l2.val)) {
            node.next = l2;
            this.nodeList(l1, l2.next, node.next);
        }

    }

}

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}
